﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;

namespace 线程锁
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            #region MyRegion

           // lizi1();
            lizi2();
            stateObject state=new stateObject();
            for (int i = 0; i < 20; i++)
            {
                new Task(new SampleTask().RaceCondition,state).Start();
                Thread.Sleep(10000);
            }
            #endregion

            Console.ReadKey();
        }

        private static void lizi1()
        {
            int num = 0;

            var t1 = new Thread(() =>
            {
                for (int i = 0; i < 10000000; i++)
                {
                    lock ("s")
                    {
                        num++;
                    }
                }
            });
            t1.IsBackground = true;
            t1.Start();


            for (int i = 0; i < 10000000; i++)
            {
                lock ("s")
                {
                    num--;
                }
            }
            t1.Join();
            Console.WriteLine(num.ToString());
        }

        private static void lizi2()
        {
           
        }
        public class stateObject
        {
            private int state = 5;

            public void changeState(int loop)
            {
                if (state==5)
                {
                    state++;
                    Trace.Assert(state==6,"Race condition occurred after"+loop+"loops");
                }
                state = 5;
            }
        }

        public class SampleTask
        {
            public void RaceCondition(object o)
            {
                Trace.Assert(o is stateObject,"o must be type of stateobject");
                stateObject state = o as stateObject;

                int i = 0;
                while (true)
                {
                    state.changeState(i++);
                } 
            }
        }
        
    }
}